﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Framework.Services;
using Domain.Module.Entities;
using Framework.Repositories;
using Domain.Specification.Users;
using Infrastructure.QueryServices;
using Framework.Infrastructure;
using Infrastructure.DataObjects;
using Framework.UnitOfWork;
using Domain.Repositories;
using Framework.Infrastructure.IoC;
using Microsoft.Practices.Unity;

namespace Application.AppServices.UserManagement
{
    class UserManagementService : ApplicationService, IUserManagementService
    {
        public UserManagementService(IUnitOfWork unitOfWork) : base(unitOfWork)
        {}

        IRepository<User> UserRepository
        {
            get
            {
                return GetRepository<User>();
            }
        }

        IUserRepository UserRepository2
        {
            get
            {
                return IoCFactory.Instance.CurrentContainer.Resolve<IUserRepository>();
            }
        }

        public void AddUser(UserObject userObject)
        {
            DoAddUser(userObject);
            UnitOfWork.Commit();
        }

        public void AddUsers(List<UserObject> userObjects)
        {
            userObjects.ForEach(userObject => DoAddUser(userObject));
            UnitOfWork.Commit();
        }

        protected virtual void DoAddUser(UserObject userObject)
        {
            User user = User.CreateUser(userObject);
            UserRepository2.Add(user);
        }

        public virtual void UpdateUser(UserObject userObject)
        {
            var user = UserRepository.GetByKey(userObject.ID);
            if (user != null)
            {
                user.Update(userObject);
                UnitOfWork.Commit();
            }
        }
    }
}
